package com.txsj.scan.presenter;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import com.greendao.RecordInfoDao;
import com.greendao.TagGroupInfoDao;
import com.txsj.scan.Constants;
import com.txsj.scan.base.BasePresenter;
import com.txsj.scan.bean.BaseListResult;
import com.txsj.scan.bean.RecordInfo;
import com.txsj.scan.bean.TagGroupInfo;
import com.txsj.scan.db.GreenDaoUtils;
import com.txsj.scan.http.ApiServer;
import com.txsj.scan.http.requestframework.RetrofitManager;
import com.txsj.scan.utils.MD5Util;
import com.txsj.scan.utils.PreferenceUtil;
import com.txsj.scan.utils.Trace;
import com.txsj.scan.view.IUnbindLabelView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * @Created by WangChuangJun on 2019/2/20
 * @Describe
 */
public class UnbindLabelPresenter extends BasePresenter<IUnbindLabelView> {

    private static final int ON_LOADING = 0x250;
    private static final int ON_ERROR = 0x251;
    private static final int ON_SUCCESS = 0x252;
    private static final int RETRY_LOAD = 0x253;
    private Thread cacheThread;
    private List<RecordInfo> recordInfoList;

//    private long times_long = 1000*60*30;//时间差
    private long times_long = 1000*6;//时间差

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case ON_LOADING:
                    view.onLoading();
                    break;
                case ON_ERROR://首次加载失败
                    String error_msg = (String) msg.obj;
                    view.onError(error_msg);
                    break;
                case ON_SUCCESS://首次加载成功
                    view.onSuccess();
                    break;
                case RETRY_LOAD://重试
                    gotoHttpData();
                    break;
            }
        }
    };

    public UnbindLabelPresenter(IUnbindLabelView view) {
        super(view);
    }

    @Override
    protected void initModel() {

    }

    /**
     * 缓存标签组信息
     */
    public void cacheTagGroupInfo() {
        recordInfoList= GreenDaoUtils.getSingleTon().getmDaoSession().getRecordInfoDao().queryBuilder()
                .where(RecordInfoDao.Properties.Type.eq(Constants.TAG_GROUP_INFO))
                .list();
        if (null == recordInfoList || recordInfoList.size() == 0){//如果为空说明是第一次进来直接进行缓存
            gotoHttpData();
        }else {
            if ( System.currentTimeMillis() -recordInfoList.get(0).getUpdate_time() >= times_long){
                gotoHttpData();
                Trace.e("wcj更新时间：======"+recordInfoList.get(0).getUpdate_time());
            }
        }


    }

    private void gotoHttpData() {
        cacheThread = new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                getTagGroupInfo();
                Looper.loop();
            }
        });
        cacheThread.start();
    }


    private int retryLabelCount = 0;//重试次数
    private int reTryLabelMax = 20;//重试最大次数，超过就关闭
    private long reTryLabelDelay = 1500;//重试间隔，1.5s
    private int page = 1;//请求页码，从一开始
    private int limit = 20;//数据size()

    /**
     * 缓存已经预绑定的标签信息
     * 从page=1开始请求
     */
    public void getTagGroupInfo() {
        Map<String, String> params = new HashMap<>();
        StringBuilder builder = new StringBuilder();
        builder.append(PreferenceUtil.getInstance().getString(PreferenceUtil.BRAND_ID, ""));
        builder.append("|");
        builder.append(PreferenceUtil.getInstance().getInt(PreferenceUtil.USER_ID, 0));
        builder.append("|");
        builder.append(PreferenceUtil.getInstance().getString(PreferenceUtil.TOKEN, ""));
        builder.append("|");
        builder.append(0);
        builder.append("|");
        params.put("brandtoken", builder.toString());
        params.put("limit", limit+"");
        params.put("page", page + "");
        params.put("isbind", "false");
        params.put("timeStamp", System.currentTimeMillis() / 1000 + "");//加时间戳参数
        params.put("sign", MD5Util.md5(params));//md5加密并加参数
        if (page <= 1) handler.sendEmptyMessage(ON_LOADING);
        if (retryLabelCount != 0){
            Trace.e("重连次数："+ retryLabelCount);
        }
        RetrofitManager.getDefault().create(ApiServer.class).getTagGroupList(RetrofitManager
                .getHeader(), params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.from(Looper.myLooper()))
                .subscribe(new Observer<BaseListResult<TagGroupInfo>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        compositeDisposable.add(d);
                    }

                    @Override
                    public void onNext(BaseListResult<TagGroupInfo> result) {
                        if (result.isSuccess()) {
                            if (null != result.getData() && result.getData().size() > 0) {
                                setDataToSql(result.getData());
                            } else {
                                if (page > 1){
                                    handler.sendEmptyMessage(ON_SUCCESS);
                                }else {
                                    retryLabelCount = 0;//重置
                                    Message msg = new Message();
                                    msg.obj = "暂无数据";
                                    msg.what = ON_ERROR;
                                    handler.sendMessage(msg);
                                }
                            }
                        } else {
                            // TODO 网络异常
                            if (retryLabelCount < reTryLabelMax) {
                                retryLabelCount++;
                                Message msg = new Message();
                                msg.what = RETRY_LOAD;
                                handler.sendMessageDelayed(msg, reTryLabelDelay);
                            }else {
                                retryLabelCount = 0;//重置
                                Message msg = new Message();
                                msg.obj = "网络异常";
                                msg.what = ON_ERROR;
                                handler.sendMessage(msg);
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        Trace.e("wcj,Tag+++++：" + t.getMessage());
                        if (retryLabelCount < reTryLabelMax) {
                            retryLabelCount++;
                            Message msg = new Message();
                            msg.what = RETRY_LOAD;
                            handler.sendMessageDelayed(msg, reTryLabelDelay);
                        }else {
                            retryLabelCount = 0;//重置
                            Message msg = new Message();
                            msg.obj = "网络异常";
                            msg.what = ON_ERROR;
                            handler.sendMessage(msg);
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    /**
     * 将请求回来的数据放到数据库中
     * @param data
     */
    private void setDataToSql(final List<TagGroupInfo> data) {
        final TagGroupInfoDao tagGroupInfoDao = GreenDaoUtils.getSingleTon().getmDaoSession().getTagGroupInfoDao();
        if (page == 1 && tagGroupInfoDao.loadAll().size() > 0){
            tagGroupInfoDao.deleteAll();
        }
        tagGroupInfoDao.getSession().runInTx(new Runnable() {
                    @Override
                    public void run() {
                        tagGroupInfoDao.insertInTx(data);
                    }
                });

        //判断是否未加载完毕
        if (data.size() % limit == 0) {
            page++;
            getTagGroupInfo();
        } else {
            handler.sendEmptyMessage(ON_SUCCESS);
        }

        //对更新后的数据进行记录
        if (null == recordInfoList || recordInfoList.size() == 0){
            RecordInfo recordInfo = new RecordInfo();
            recordInfo.setType(Constants.TAG_GROUP_INFO);
            recordInfo.setUpdate_time(System.currentTimeMillis());
            recordInfo.setWarehouse_id("-5");
            GreenDaoUtils.getSingleTon().getmDaoSession().getRecordInfoDao().insertOrReplace(recordInfo);
        }else {
            if ( System.currentTimeMillis() - recordInfoList.get(0).getUpdate_time() >= times_long){
                recordInfoList.get(0).setUpdate_time(System.currentTimeMillis());
                GreenDaoUtils.getSingleTon().getmDaoSession().getRecordInfoDao().insertOrReplace(recordInfoList.get(0));
                Trace.e("wcj最新更新时间：======"+recordInfoList.get(0).getUpdate_time());
            }
        }
    }
}
